package com.okb.utils;

import com.alibaba.fastjson2.JSON;
import com.okb.bean.ResponseBean;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URI;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 * Author: hcxu
 * Time: 2024/11/18 3:35 PM
 */
public class HttpUtils {
    //@Value("${okb.owner.apikey}")
    public static final String apiKey = "c3748fd1-02a5-4e22-8249-d09e5d1970b7";

    //@Value("${okb.owner.passphrase}")
    public static final String passphrase = "Xu19950713.";

    public static final String secretKey = "AB7049F2433992382545C74A05315E32";

    public static final String method_pre = "https://www.okx.com";

    public static final String REQUEST_TYPE_POST = "POST";

    public static Map<String, String> getHeader(String method,String requestType,String body) throws Exception {
        Map<String, String> result = new HashMap<>();
        //时间
        String isoTime = DateTimeFormatter.ISO_INSTANT.format(Instant.now().atZone(ZoneId.of("Asia/Tokyo")));
        StringBuffer signBuffer = new StringBuffer();
        signBuffer.append(isoTime).append(requestType).append(method);
        if(StringUtils.isNotBlank(body)){
            signBuffer.append(body);
        }
        String sign = encryptHMACSHA256(signBuffer.toString(), secretKey);
        result.put("OK-ACCESS-KEY",apiKey);
        result.put("OK-ACCESS-SIGN",sign);
        result.put("OK-ACCESS-TIMESTAMP",isoTime);
        result.put("OK-ACCESS-PASSPHRASE",passphrase);
        result.put("content-type","application/json");
        result.put("x-simulated-trading","1");
        return result;
    }

    public static String encryptHMACSHA256(String data, String secret) throws Exception {
        // 创建HMAC SHA256实例
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        mac.init(secretKeySpec);

        // 进行加密
        byte[] hmacBytes = mac.doFinal(data.getBytes());

        // 使用Base64编码返回加密结果
        return Base64.getEncoder().encodeToString(hmacBytes);
    }


    public static <T> ResponseBean<T> postRequestJson(String url, String json, Map<String,String> header, Class<T> responseType) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        T resultData = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (MapUtils.isNotEmpty(header)){
                header.forEach(httpPost::addHeader);
            }
            // 创建请求内容
            if(StringUtils.isNotBlank(json)){
                StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            ResponseBean<T> responseBean = JSON.parseObject(resultString, ResponseBean.class);
            List<T> ts = JSON.parseArray(responseBean.getData().toString(), responseType);
            responseBean.setData(ts);
            return responseBean;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new ResponseBean<>();
    }

    public static String getRequest(String url, Map<String, String> params, Map<String,String> header) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (params != null) {
                for (String key : params.keySet()) {
                    builder.addParameter(key, params.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            if (MapUtils.isNotEmpty(header)){
                header.forEach(httpGet::addHeader);
            }
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


}
